<template>
  <div class="lawyer-list-view">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">专业律师团队</h1>
      <p class="page-subtitle">经验丰富、专业可靠的执业律师，为您提供全方位的法律服务</p>
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <div class="filter-left">
        <el-input
          v-model="searchQuery"
          placeholder="搜索律师姓名、专业领域..."
          class="search-input"
          :prefix-icon="Search"
          clearable
          @input="handleSearch"
        />

        <el-select
          v-model="specialtyFilter"
          placeholder="专业领域"
          class="specialty-select"
          clearable
          @change="handleFilter"
        >
          <el-option
            v-for="specialty in specialties"
            :key="specialty"
            :label="specialty"
            :value="specialty"
          />
        </el-select>

        <el-select
          v-model="experienceFilter"
          placeholder="执业年限"
          class="experience-select"
          clearable
          @change="handleFilter"
        >
          <el-option
            v-for="exp in experienceOptions"
            :key="exp.value"
            :label="exp.label"
            :value="exp.value"
          />
        </el-select>
      </div>

      <div class="filter-right">
        <el-button :type="sortBy === 'rating' ? 'primary' : ''" @click="changeSort('rating')">
          <el-icon><Star /></el-icon>
          按评分排序
        </el-button>

        <el-button
          :type="sortBy === 'experience' ? 'primary' : ''"
          @click="changeSort('experience')"
        >
          <el-icon><TrendCharts /></el-icon>
          按经验排序
        </el-button>
      </div>
    </div>

    <!-- 律师列表 -->
    <div class="lawyer-list-container">
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="6" animated />
      </div>

      <div v-else-if="lawyers.length === 0" class="empty-state">
        <el-empty description="暂无符合条件的律师">
          <el-button type="primary" @click="resetFilters">重置筛选条件</el-button>
        </el-empty>
      </div>

      <div v-else class="lawyer-grid">
        <div
          v-for="lawyer in lawyers"
          :key="lawyer.id"
          class="lawyer-card"
          @click="viewLawyerDetail(lawyer.id)"
        >
          <div class="card-header">
            <div class="lawyer-avatar">
              <el-avatar :size="80" :src="lawyer.avatar" />
              <div v-if="lawyer.isOnline" class="online-indicator"></div>
            </div>

            <div class="lawyer-basic-info">
              <h3 class="lawyer-name">{{ lawyer.name }}</h3>
              <p class="lawyer-title">{{ lawyer.title }}</p>
              <div class="lawyer-rating">
                <el-rate
                  :model-value="lawyer.rating"
                  disabled
                  show-score
                  text-color="#ff9900"
                  score-template="{value} 分"
                />
              </div>
            </div>
          </div>

          <div class="specialty-tags">
            <el-tag
              v-for="specialty in lawyer.specialties"
              :key="specialty"
              type="info"
              size="small"
            >
              {{ specialty }}
            </el-tag>
          </div>

          <div class="lawyer-stats">
            <div class="stat-item">
              <span class="stat-label">执业年限</span>
              <span class="stat-value">{{ lawyer.experience }} 年</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">成功案例</span>
              <span class="stat-value">{{ lawyer.caseCount }} 件</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">咨询费用</span>
              <span class="stat-value price">¥{{ lawyer.hourlyRate }}/小时</span>
            </div>
          </div>

          <div class="lawyer-description">
            <p>{{ lawyer.description }}</p>
          </div>

          <div class="card-actions">
            <el-button type="primary" class="consult-btn" @click.stop="appointLawyer(lawyer.id)">
              <el-icon><ChatDotRound /></el-icon>
              立即预约
            </el-button>
            <el-button class="detail-btn" @click.stop="viewLawyerDetail(lawyer.id)">
              查看详情
            </el-button>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="total > 0" class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[9, 12, 18, 24]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, inject } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus'
import { Search, Star, TrendCharts, ChatDotRound } from '@element-plus/icons-vue'

const router = useRouter()
const api = inject('$api')

// 响应式数据
const searchQuery = ref('')
const specialtyFilter = ref('')
const experienceFilter = ref('')
const sortBy = ref('rating')
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(9)
const total = ref(0)

// 数据列表
const lawyers = ref([])
const specialties = ref([])

// 执业年限选项
const experienceOptions = ref([
  { value: '1-3', label: '1-3年' },
  { value: '3-5', label: '3-5年' },
  { value: '5-10', label: '5-10年' },
  { value: '10+', label: '10年以上' },
])

// 防抖搜索
let searchTimeout = null

// 方法
const fetchLawyers = async () => {
  try {
    loading.value = true

    const searchParams = {
      searchQuery: searchQuery.value || null,
      specialtyFilter: specialtyFilter.value || null,
      experienceFilter: experienceFilter.value || null,
      sortBy: sortBy.value,
      page: currentPage.value,
      pageSize: pageSize.value,
    }

    const response = await api.lawyers.getLawyerList(searchParams)

    if (response.code === 200) {
      lawyers.value = response.data.records
      total.value = response.data.total
    } else {
      ElMessage.error(response.message || '获取律师列表失败')
      lawyers.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('获取律师列表失败:', error)
    ElMessage.error('网络错误，请稍后重试')
    lawyers.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

const fetchSpecialties = async () => {
  try {
    const response = await api.lawyers.getSpecialties()
    if (response.code === 200) {
      specialties.value = response.data
    }
  } catch (error) {
    console.error('获取专业领域失败:', error)
  }
}

const handleSearch = () => {
  clearTimeout(searchTimeout)
  searchTimeout = setTimeout(() => {
    currentPage.value = 1
    fetchLawyers()
  }, 500)
}

const handleFilter = () => {
  currentPage.value = 1
  fetchLawyers()
}

const changeSort = (type) => {
  sortBy.value = type
  fetchLawyers()
}

const resetFilters = () => {
  searchQuery.value = ''
  specialtyFilter.value = ''
  experienceFilter.value = ''
  currentPage.value = 1
  fetchLawyers()
}

const handleSizeChange = (newSize) => {
  pageSize.value = newSize
  currentPage.value = 1
  fetchLawyers()
}

const handleCurrentChange = (newPage) => {
  currentPage.value = newPage
  fetchLawyers()
}

const appointLawyer = (lawyerId) => {
  router.push({
    name: 'LawyerAppointment',
    query: { lawyerId: lawyerId },
  })
}

const viewLawyerDetail = async (lawyerId) => {
  ElMessage.info(`查看律师详情 ID: ${lawyerId}`)
}

// 监听页面变化
watch([currentPage], () => {
  fetchLawyers()
})

// 生命周期
onMounted(async () => {
  await Promise.all([fetchSpecialties(), fetchLawyers()])
})
</script>

<style scoped>
.lawyer-list-view {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

/* 页面标题样式 */
.page-header {
  margin-bottom: 30px;
  text-align: center;
}

.page-title {
  font-size: 2.5rem;
  color: #1a3a5f;
  margin: 15px 0 10px;
  font-weight: 700;
}

.page-subtitle {
  font-size: 1.1rem;
  color: #666;
  max-width: 600px;
  margin: 0 auto;
}

/* 筛选区域样式 */
.filter-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding: 20px;
  background: #f9fafb;
  border-radius: 8px;
  flex-wrap: wrap;
  gap: 15px;
}

.filter-left {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.search-input {
  width: 280px;
}

.specialty-select,
.experience-select {
  width: 150px;
}

.filter-right {
  display: flex;
  gap: 10px;
}

/* 律师列表容器 */
.lawyer-list-container {
  min-height: 500px;
}

.loading-container {
  padding: 40px 0;
}

.empty-state {
  padding: 60px 0;
  text-align: center;
}

/* 律师网格布局 */
.lawyer-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 24px;
  margin-bottom: 30px;
}

/* 律师卡片样式 */
.lawyer-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  padding: 24px;
  transition: all 0.3s ease;
  cursor: pointer;
  border: 1px solid #f0f0f0;
}

.lawyer-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}

.lawyer-avatar {
  position: relative;
  margin-right: 16px;
}

.lawyer-basic-info {
  flex: 1;
}

.lawyer-name {
  font-size: 1.3rem;
  font-weight: 600;
  color: #1a3a5f;
  margin: 0 0 5px;
}

.lawyer-title {
  color: #666;
  margin: 0 0 10px;
  font-size: 0.9rem;
}

.lawyer-rating {
  margin-top: 5px;
}

/* 专业标签样式 */
.specialty-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-bottom: 16px;
}

/* 统计信息样式 */
.lawyer-stats {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
  margin-bottom: 16px;
  padding: 12px;
  background: #f9fafb;
  border-radius: 8px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.stat-label {
  font-size: 0.8rem;
  color: #666;
  margin-bottom: 4px;
}

.stat-value {
  font-weight: 600;
  color: #1a3a5f;
}

.stat-value.price {
  color: #ff6b35;
}

/* 律师描述 */
.lawyer-description {
  margin-bottom: 20px;
}

.lawyer-description p {
  color: #666;
  font-size: 0.9rem;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 卡片操作按钮 */
.card-actions {
  display: flex;
  gap: 10px;
}

.consult-btn {
  flex: 2;
  background: linear-gradient(135deg, #1a3a5f 0%, #2c5282 100%);
  border: none;
  font-weight: 600;
}

.detail-btn {
  flex: 1;
  border-color: #1a3a5f;
  color: #1a3a5f;
}

.detail-btn:hover {
  background: rgba(26, 58, 95, 0.1);
}

/* 分页样式 */
.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .lawyer-list-view {
    padding: 15px;
  }

  .filter-section {
    flex-direction: column;
    align-items: stretch;
  }

  .filter-left {
    flex-direction: column;
  }

  .search-input,
  .specialty-select,
  .experience-select {
    width: 100%;
  }

  .lawyer-grid {
    grid-template-columns: 1fr;
  }

  .card-actions {
    flex-direction: column;
  }
}

@media (max-width: 480px) {
  .page-title {
    font-size: 2rem;
  }

  .lawyer-stats {
    grid-template-columns: 1fr;
    gap: 8px;
  }
}
</style>
